#include "stm32f10x.h" // Device header

/**
 * 初始化定时器
 * 本函数用于初始化TIM2定时器，配置其为向上计数模式，周期为1000ms，并开启TIM2的中断。
 * 不接受参数，也不返回任何值。
 */
void Timer2_Init(void)
{
    // 启用TIM2时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    // 使用内部时钟配置TIM2
    TIM_InternalClockConfig(TIM2);

    // 初始化TIM2的时间基座配置
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
    TIM_TimeBaseInitStructure.TIM_ClockDivision     = TIM_CKD_DIV1;       // 时钟分频设置
    TIM_TimeBaseInitStructure.TIM_CounterMode       = TIM_CounterMode_Up; // 计数模式设置为向上计数
    TIM_TimeBaseInitStructure.TIM_Period            = 10000 - 1;          // 定时器周期设置，对应1000ms
    TIM_TimeBaseInitStructure.TIM_Prescaler         = 7200 - 1;           // 预分频器设置
    TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;                  // 循环计数器设置
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure);

    // 清除定时器更新标志，并开启更新事件中断
    TIM_ClearFlag(TIM2, TIM_FLAG_Update);
    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);

    // 配置NVIC的优先级组
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

    // 初始化NVIC的定时器2中断配置
    NVIC_InitTypeDef NVIC_InitStructure;
    NVIC_InitStructure.NVIC_IRQChannel                   = TIM2_IRQn; // 定时器2中断通道
    NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;    // 启用中断
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;         // 预优先级设置
    NVIC_InitStructure.NVIC_IRQChannelSubPriority        = 1;         // 子优先级设置
    NVIC_Init(&NVIC_InitStructure);

    // 启用定时器
    TIM_Cmd(TIM2, ENABLE);
}

void Timer1_Init()
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);

    TIM_InternalClockConfig(TIM1);

    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
    TIM_TimeBaseInitStructure.TIM_ClockDivision     = TIM_CKD_DIV1;
    TIM_TimeBaseInitStructure.TIM_CounterMode       = TIM_CounterMode_Up;
    TIM_TimeBaseInitStructure.TIM_Period            = 5000- 1;
    TIM_TimeBaseInitStructure.TIM_Prescaler         = 7200 - 1;
    TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStructure);

    TIM_ClearFlag(TIM1, TIM_FLAG_Update);
    TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE);

    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

    NVIC_InitTypeDef NVIC_InitStructure;
    NVIC_InitStructure.NVIC_IRQChannel                   = TIM1_UP_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority        = 1;
    NVIC_Init(&NVIC_InitStructure);

    TIM_Cmd(TIM1, ENABLE);
}

